<template>
  <div class="user-login flex-center-center">
    <img src="@/assets/imgs/login-bg.jpg" class="login-bg" />
    <div class="login-form">
      <h1 class="login-form-title">登录</h1>
      <el-form ref="form" size="large">
        <el-form-item>
          <el-input v-model="formData.username" class="account" placeholder="用户名" />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formData.password"
            class="password"
            placeholder="密码"
            show-password
            @keyup.enter="onLogin"
          />
        </el-form-item>

        <el-form-item class="inline-with-btn">
          <el-input
            v-model="formData.code"
            class="code-input"
            placeholder="请输入"
            @change="onLogin"
          />
          <img :src="img" width="112" height="40" style="margin-left: auto;" @click="getCaptchaImage">
        </el-form-item>

        <el-button class="login-btn" type="primary" @click="onLogin">
          登 录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup>
// import { mapActions, mapMutations } from 'vuex';
import { onBeforeMount, reactive, ref } from 'vue';
import { loginApi, getCaptchaImageApi } from '@/api/login';
import encrypt from '@/utils/aes.js';
import useUser from '@/hooks/useUser.js';
import useToken from '@/hooks/useToken.js';
import router from '@/router';
import { useRoute } from 'vue-router';

const route = useRoute();
const [, setUser] = useUser();
const { setToken } = useToken();

const loading = ref(false);

const formData = reactive({
  username: 'adminboss',
  password: 'Hello@1234',
  code: '',
  uuid: '',
});

const img = ref('');

onBeforeMount(() => {
  getImageCaptcha();
});

const getImageCaptcha = async () => {
  const data = await getCaptchaImageApi();
  img.value = `data:image/png;base64,${data.img}`;
  formData.uuid = data.uuid;
};

const onLogin = async () => {
  loading.value = true;
  const params = {
    ...formData,
    password: encrypt(formData.password),
  };
  const { token } = await loginApi(params).finally(() => {
    loading.value = false;
  });

  setToken(token);

  const newUser = {
    username: formData.username,
  };
  setUser(newUser);
  router.push({ name: 'home',
    ...(route.query.to ? { query: route.query.to } : {}) });
};
</script>

<style src="./index.less" lang="less" scoped />
